package com.chaodev.base.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.chaodev.base.base.RedisDao;
import com.chaodev.base.dao.LearningRecordDao;
import com.chaodev.base.dao.TrainingDao;
import com.chaodev.base.dto.LearningRecordDto;
import com.chaodev.base.model.LearningRecord;
import com.chaodev.base.model.Result;
import com.chaodev.base.model.Training;
import com.chaodev.base.model.UserInfo;
import com.chaodev.base.service.ILogService;
import com.chaodev.base.service.LearningRecordService;
import com.chaodev.base.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
public class LearningRecordServiceImpl implements LearningRecordService {
    @Autowired
    private RedisDao redisDao;
    @Autowired
    private ILogService logService;

    @Autowired
    private LearningRecordDao learningRecordDao;
    @Autowired
    private TrainingDao trainingDao;

    @Override
    public Result queryLearningRecord(Integer trainingId, String beginTime, String endTime, HttpServletRequest request ,Integer page,Integer rows) {
        Result result = Result.success(null, "查询成功");
        String token = request.getHeader("token");
        UserInfo userInfo = null;
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);

            Map<String, Object> map = new HashMap<>();
            map.put("trainingId", trainingId);
            if (userInfo.getRoleId().equals("1000")){
                map.put("roleId",userInfo.getRoleId());
            }else {
                map.put("userId", userInfo.getUserId());
            }
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            if(null==page||page==0){
                page=1;
            }
            if(null==rows||rows==0){
                rows=20;
            }
            PageHelper.startPage(page, rows);
            List<LinkedHashMap<String, Object>> list = learningRecordDao.queryData(map);
            PageInfo<LinkedHashMap<String, Object>> pageList = new PageInfo<>(list,rows);

            result.setData(pageList);
            logService.logAdd(map.toString(), "查询学习记录", "SUCCESS", result.toString(), userInfo, request);
        } else {
            result = Result.error("登录超时");
            logService.logAdd(null, "查询学习记录", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    @Override
    public Result addLearningRecord(LearningRecordDto dto, HttpServletRequest request) {
        Result result = Result.success(null, "学习记录添加成功！");
        String token = request.getHeader("token");
        UserInfo userInfo = null;
        //校验数据
        Training training = trainingDao.findDataById(dto.getTrainingId());
        if (training == null) {
            result.setCode(404);
            result.setMsg("课程不存在");
            logService.logAdd(dto.toString(), "提交学习记录", "ERROR", result.toString(), userInfo, request);
            return result;
        }
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);

            //根据课程ID查询学习记录
            List<LearningRecord> oldList = learningRecordDao.queryDataByTrainingId(dto.getTrainingId());
            long hour = 0L;
            long inputHour = Duration.between(dto.getStartTime(), dto.getCommitTime()).toMillis();
            if (null != oldList && oldList.size() > 0) {
                long millis = oldList.stream().mapToLong(r -> Duration.between(r.getCreateTime(), r.getUpdateTime()).toMillis()).sum();
                hour = (millis + inputHour) / 3600000L;
            }
            //不存在,添加学习记录
            LearningRecord record = new LearningRecord();
            record.setTrainingId(dto.getTrainingId());
            record.setUserId(userInfo.getUserId());
            record.setStatus(training.getLearningDuration() > hour ? 1 : 2);
            record.setCreateTime(dto.getStartTime());
            record.setUpdateTime(dto.getCommitTime());
            learningRecordDao.insert(record);
            logService.logAdd(dto.toString(), "提交学习记录", "SUCCESS", result.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(dto.toString(), "提交学习记录", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }
}
